package com.tanhua.manager.service;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.Admin;
import com.tanhua.dubbo.api.db.AdminApi;
import com.tanhua.manager.exceptions.TanhuaException;
import com.tanhua.manager.interceptors.AdminHolder;
import com.tanhua.manager.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminService {

    @Autowired
    private StringRedisTemplate redisTemplate;


//    存储token的前缀
    private static final String CACHE_KEY_TOKEN_PREFIX="MANAGE_TOKEN_";
//  存储验证码的前缀
    private static final String CACHE_KEY_CAP_PREFIX = "MANAGE_CAP_";


    //根据登录token，获取用户对象
    public Admin findAdminByToken(String token) {
        String adminStr = redisTemplate.boundValueOps(CACHE_KEY_TOKEN_PREFIX+token).get();
        if(adminStr == null) {
            return null;
        }
        redisTemplate.boundValueOps(CACHE_KEY_TOKEN_PREFIX+token).set(adminStr,2, TimeUnit.HOURS);//续期
        return JSON.parseObject(adminStr,Admin.class);
    }


    /**
     * 从redis中删除token缓存
     */
    public void removeToken(String token){
        String redisTokenKey = CACHE_KEY_TOKEN_PREFIX + token;
        this.redisTemplate.delete(redisTokenKey);
    }

    public ResponseEntity verification(HttpServletResponse response,String uuid) throws Exception {
//        1、生成一个验证码图片
//        CAPTCHA
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 100);
        lineCaptcha.write(response.getOutputStream());

//        2、从图片中获取内容放到redis中
//        String captchaCode = lineCaptcha.getCode();
        String captchaCode = "123456"; //TODO 正式上线时要放开

        redisTemplate.boundValueOps(CACHE_KEY_CAP_PREFIX+uuid).set(captchaCode,10,TimeUnit.MINUTES);


        return ResponseEntity.ok(null);
    }

    @Reference
     private AdminApi adminApi;

    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        String captchaCode = redisTemplate.boundValueOps(CACHE_KEY_CAP_PREFIX + uuid).get();
//        有可能为空
        if(StringUtils.isBlank(captchaCode)){
            throw new TanhuaException(500,"验证码已失效");
        }
        if(!StringUtils.equals(captchaCode,verificationCode)){
            throw new TanhuaException(500,"验证码错误");
        }
//        根据用户名查询
        Admin admin = adminApi.findByUsername(username);
        if (admin==null){
            throw new TanhuaException(500,"用户名错误");
        }

//        比较密码 先把页面上输入的加密
        password = DigestUtils.md5Hex(password);
        if(!StringUtils.equals(admin.getPassword(),password)){
            throw new TanhuaException(500,"密码错误");
        }

//        通过jwt生成token
        String token = JwtUtils.createToken(username, admin.getId(), "class154");

//        token设置2小时有效
        redisTemplate.boundValueOps(CACHE_KEY_TOKEN_PREFIX+token).set(JSON.toJSONString(admin),2,TimeUnit.HOURS);


        Map map = new HashMap();
        map.put("token",token);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity logout() {
        String token = AdminHolder.getAdmin().getToken();

        redisTemplate.delete(CACHE_KEY_TOKEN_PREFIX+token);
        return ResponseEntity.ok(null);

    }
}